package com.XZDP.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
 * redis自增生成工具类
 * 符号位+时间戳(秒)+redis自增返回值
 */
@Component
public class RedisID {
    //时间戳起点(秒)
    private final Long timestamp = 1731506644L;
    @Autowired
    private StringRedisTemplate redisTemplate;
    private final String ICY_KEY = "icy:";

    /**
     * @param business 传入业务名作为KEY拼接前缀
     * @return
     */
    public Long GetID(String business) {
        //获取当前时间秒值
        LocalDateTime now = LocalDateTime.now();
        long second = now.toEpochSecond(ZoneOffset.UTC);
        long time = second - timestamp;
        //获取redis自增返回值
        String data = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        Long increment = redisTemplate.opsForValue().increment(ICY_KEY + business + ":" + data);
        return time << 32 | increment;
    }
}

